package com.wavercaz.freeforum.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wavercaz.freeforum.pojo.Admin;
import com.wavercaz.freeforum.pojo.User;
import com.wavercaz.freeforum.pojo.UserDetail;
import com.wavercaz.freeforum.services.AdminService;
import com.wavercaz.freeforum.services.UserService;
import com.wavercaz.freeforum.utils.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private LoginUtil loginUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetail userDetail = null;
        if(loginUtil.getType().equals("user")) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            userDetail = userService.getOne(queryWrapper.eq("username", username));
            if(userDetail == null) {
                userDetail = new User();
            }
        } else {
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            userDetail = adminService.getOne(queryWrapper.eq("username", username));
            if(userDetail == null) {
                userDetail = new Admin();
            }
        }
        return new NewUserDetails(userDetail);
    }
}
